package com.fenfen.novel;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Parcelable;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewCompat;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.afollestad.materialdialogs.MaterialDialog;
import com.fenfen.novel.adapter.ChapterAdapter;
import com.fenfen.novel.db.NovelReadRecord;
import com.fenfen.novel.model.Chapter;
import com.fenfen.novel.model.Novel;
import com.fenfen.novel.rest.RestClient;
import com.fenfen.novel.service.NovelDownService;
import com.fenfen.novel.utils.ChapterListUtil;
import com.fenfen.novel.utils.CommonUtil;
import com.fenfen.novel.utils.NovelRecordHandlerThread;
import com.fenfen.novel.utils.NovelRecordUtil;
import com.squareup.picasso.Picasso;

import org.parceler.Parcels;

import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class NovelActivity extends BaseActivity implements View.OnClickListener, ChapterAdapter.ChapterClickListener {

  private static String Tag = NovelActivity.class.getSimpleName();

  public static final String EXTRA_NOVEL_ENTITY = "NOVEL_ENTITY";

  public static final String VIEW_NAME_HEADER_IMAGE = "header:image";

  private Novel novel;

  private ImageView novelCover;
//  private RecyclerView recyclerView;

  private ChapterAdapter preListAdapter, allListAdapter;
  private boolean isLoadingAll;
  private ChapterListUtil chapterListUtil;

  private ProgressBar loadingProgress;
  private CommonUtil.CallbackListener mCallbackListener;

  private NovelRecordHandlerThread dbThread;

  private String novelDownStatus = null;

  private Button downBtn;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_novel);

    chapterListUtil = new ChapterListUtil(this);

    Parcelable parcelable = getIntent().getParcelableExtra(EXTRA_NOVEL_ENTITY);
    novel = Parcels.unwrap(parcelable);

    initToolbar();
    initView();

    ViewCompat.setTransitionName(novelCover, VIEW_NAME_HEADER_IMAGE);

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.chapters_list);
    preListAdapter = new ChapterAdapter(this);
    chapterListUtil.initChaptersRecyclerView(recyclerView, true, preListAdapter);
    mCallbackListener = new MyCallbackListener();
    chapterListUtil.loadNovelPreChapters(novel.getId(), preListAdapter, mCallbackListener);

    dbThread = new NovelRecordHandlerThread(this, new Handler());
    dbThread.start();
    dbThread.setHandlerListener(new MyDbListener());
    dbThread.queryDownInfoByNovelId(novel.getId());
  }

  private class MyCallbackListener implements CommonUtil.CallbackListener {
    @Override
    public void onResponse() {
      hideProgress();
    }

    @Override
    public void onFailure() {
      hideProgress();
      CommonUtil.showSnackRetry(loadingProgress, R.string.get_chapter_per_list_error, new View.OnClickListener() {
        @Override
        public void onClick(View v) {
          showProgress();
          chapterListUtil.loadNovelPreChapters(novel.getId(), preListAdapter, mCallbackListener);
        }
      });
    }
  }

  private void loadNovelCover() {
    String coverlUrl = novel.getNovelCover();
    if (!TextUtils.isEmpty(coverlUrl)) {
      coverlUrl = CommonUtil.PRE_COVER_URL + coverlUrl;
      Picasso.with(this).load(coverlUrl).placeholder(R.drawable.nocover).into(novelCover);
    }
  }

  private void initToolbar() {
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(getString(R.string.novel_detail));
  }

  private void initView() {
    novelCover = (ImageView) findViewById(R.id.novel_cover);
    TextView novelName = (TextView) findViewById(R.id.novel_name);

    novelName.setText(novel.getName());
    loadNovelCover();

    setTextViewValue(R.id.novel_author, getString(R.string.novel_author_pre) + novel.getAuthor());
    setTextViewValue(R.id.novel_words, novel.getTotalWords());
    setTextViewValue(R.id.novel_chapter_count, String.format(getString(R.string.novel_chapter_count_pre), novel.getChapterCount()));
    setTextViewValue(R.id.novel_update_time, getString(R.string.novel_author_pre) + novel.getLastUpdateTime());
    setTextViewValue(R.id.novel_category, novel.getCategory());
    setTextViewValue(R.id.novel_status, novel.getStatus());
    setTextViewValue(R.id.novel_jianjie, novel.getNovelIntro());

    Button readBtn = (Button) findViewById(R.id.read_btn);
    downBtn = (Button) findViewById(R.id.down_btn);
    readBtn.setOnClickListener(this);
    downBtn.setOnClickListener(this);

    loadingProgress = (ProgressBar) findViewById(R.id.loading);
    CommonUtil.filterProgressColor(this, loadingProgress);
  }

  public void hideProgress() {
    loadingProgress.setVisibility(View.GONE);
  }

  public void showProgress() {
    loadingProgress.setVisibility(View.VISIBLE);
  }

  private void setTextViewValue(int resId, String value) {
    TextView tv = (TextView) findViewById(resId);
    tv.setText(value);
  }

  @Override
  public boolean onOptionsItemSelected(final MenuItem item) {
    int id = item.getItemId();
    switch (id) {
      case android.R.id.home: {
        super.onBackPressed();
        return true;
      }
    }
    return super.onOptionsItemSelected(item);
  }

  @Override
  public void onClick(final View v) {
    if(novelDownStatus == null) {
      CommonUtil.showSnack(v, getString(R.string.loading_novel_info));
      return;
    }
    switch (v.getId()) {
      case R.id.read_btn:
        //check read_log table,if has no record,then start from first,else read the log's order and chapter_id
//        chapter.setChapterTitle();
        //first load db read log,then load server chapter list info
        dbThread.queryByNovelId(novel.getId());
        break;
      case R.id.down_btn:
        if(novelDownStatus.equals(CommonUtil.DOWN_STATUS.SUCCESS)) {
          // TODO
          return;
        }
        //check network

        v.setEnabled(false);
        Call<String> call = RestClient.newInstance().getNovelService().showNovelDownloadStatus(novel.getId());
        call.enqueue(new Callback<String>() {
          @Override
          public void onResponse(Call<String> call, Response<String> response) {
            v.setEnabled(true);
            if (response.isSuccessful()) {
              String status = response.body();
              int msgResId = R.string.novel_down_status_success;
              if (status.contains(CommonUtil.DOWN_STATUS.NO_RESOURCE)) {
                msgResId = R.string.novel_down_status_no_resource;
              } else if (status.contains(CommonUtil.DOWN_STATUS.DOWNING)) {
                msgResId = R.string.novel_down_status_downing;
              }
              CommonUtil.showSnack(v, getString(msgResId));
              if (status.contains(CommonUtil.DOWN_STATUS.SUCCESS)) {
                //add to db
                //start service
                NovelReadRecord record = NovelRecordUtil.convertToRecordWithNovel(novel);
                dbThread.saveDownStatus(record);
                Intent novelDownService = new Intent(NovelActivity.this, NovelDownService.class);
                startService(novelDownService);
              }
            } else {
              this.onFailure(call, null);
            }
          }

          @Override
          public void onFailure(Call<String> call, Throwable t) {
            t.printStackTrace();
            v.setEnabled(true);
            CommonUtil.showSnack(v, getString(R.string.novel_down_status_error));
          }
        });
      default:
        break;
    }
  }

  private void goToChapterActivity(Chapter chapter) {
    Intent intent = new Intent(this, ChapterActivity.class);
    chapter.setNovelId(novel.getId());
    intent.putExtra(ChapterActivity.EXTRA_CHAPTER, Parcels.wrap(chapter));
    intent.putExtra(ChapterActivity.EXTRA_CHAPTER_COUNT, novel.getChapterCount());
    startActivity(intent);
  }

  @Override
  public void onItemClick(View v, Chapter chapter) {
//    Snackbar.make(v, "click activity_chapter title=" + activity_chapter.getChapterTitle() + ",order=" + activity_chapter.getChapterOrder(), Snackbar.LENGTH_SHORT).show();
    dbThread.queryByNovelIdAndChapter(novel.getId(), chapter.getChapterOrder(), chapter.getId());
    //log activity_chapter id ,activity_chapter order ,activity_chapter title,and the time,save it to db(table.read_log)
  }

  private MaterialDialog dialog;

  @Override
  public void onLoadAllItemClick(View v) {
    if (dialog == null || allListAdapter == null || allListAdapter.getItemCount() == 0) {
      //show dialog to load all chapterlist
      //before request network,check chapter_count and local table record
      allListAdapter = new ChapterAdapter(this);
      allListAdapter.setItemClickListener(this);
      int novelId = novel.getId();
      chapterListUtil.loadNovelChaptersAll(novelId, allListAdapter);
      dialog = new MaterialDialog.Builder(this)
          .title(getString(R.string.novel_chapters_list) +
              String.format(getString(R.string.novel_chapter_count_pre), novel.getChapterCount()))
          .customView(R.layout.layout_recyclerview, false)
          .positiveText(R.string.close)
          .cancelable(true)
          .autoDismiss(true).build();
      RecyclerView recyclerView = (RecyclerView) dialog.getCustomView();
      chapterListUtil.initChaptersRecyclerView(recyclerView, false, allListAdapter);
    }
    dialog.show();
  }

  private class MyDbListener extends NovelRecordHandlerThread.HandlerListener {

    @Override
    public void onQueryDownStatus(String status) {
      novelDownStatus = status;
      Log.d(Tag, "novelDownStatus=" + novelDownStatus);
      if(novelDownStatus .equals(CommonUtil.DOWN_STATUS.SUCCESS)) {
        downBtn.setText(R.string.already_download);
      }
    }

    @Override
    public void onQueryOne(NovelReadRecord record) {
      Chapter chapter = null;
      if (record != null) {
        chapter = NovelRecordUtil.convertToChapter(record);
        //update
        record = NovelRecordUtil.updateNovelRecordWithNovel(record, novel);
        dbThread.updateRecordWithNovel(record);
      } else {
        List<Chapter> chapters = preListAdapter.getData();
        if (chapters != null && chapters.size() > 0) {
          chapter = chapters.get(0);
          chapter.setNovelId(novel.getId());
          record = NovelRecordUtil.convertToRecordWithAll(chapter, novel);
          dbThread.save(record);
        }
        if (chapter == null) {
          if (loadingProgress.getVisibility() == View.GONE) {
            Snackbar.make(novelCover, getString(R.string.no_chapter_list_found), Snackbar.LENGTH_SHORT).setAction(R.string.retry, new View.OnClickListener() {
              @Override
              public void onClick(View v) {
                showProgress();
                chapterListUtil.loadNovelPreChapters(novel.getId(), preListAdapter, mCallbackListener);
              }
            }).show();
          } else {
            Snackbar.make(novelCover, getString(R.string.loading_chapter_list), Snackbar.LENGTH_SHORT).show();
          }
          return;
        }
      }
      goToChapterActivity(chapter);
    }

    @Override
    public void onQueryOne(NovelReadRecord record, int chapterOrder, int chapterId) {
      NovelReadRecord newRecord = NovelRecordUtil.convertToRecordWithAll(novel, chapterOrder, chapterId);
      if (record != null) {
        dbThread.updateRecordWithAll(newRecord);
      } else {
        dbThread.save(newRecord);
      }
      goToChapterActivity(NovelRecordUtil.convertToChapter(newRecord));
    }
  }
}
